package ricm4.ar.nio.nioEngine;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.channels.SocketChannel;


/**
 * Test class for NioEngine.
 * This class allows to start an NioEngine server (through the command 
 * java NioEngine.Test -s) and a NioEngine client (through the command
 * java NioEngine).
 * The client and server interact infinitely, pinponging
 * a small message.
 */

public class Test implements I_RecvMsgHandler{
	I_NioEngine nioEngine;
	String name;

	public Test(String[] args) throws IOException {

		if (args.length > 0 && args[0].equalsIgnoreCase("-s")){
			System.out.println("Starting nio server");
			name="server";
			InetAddress addr = InetAddress.getByName("localhost");  
			nioEngine = new NioEngine();
			nioEngine.InitializeAsServer(addr, 9090, this);
			nioEngine.mainloop();

		} else {
			System.out.println("Starting nio client");
			name="client";
			InetAddress addr = InetAddress.getByName("localhost");  
			nioEngine = new NioEngine();
			nioEngine.InitializeAsClient(addr, 9090, this);
			nioEngine.send("This is a test message".getBytes());
			nioEngine.mainloop();
		}
	}

	public void receivedCB(byte[] data, SocketChannel socketChannel){
		System.out.println(name + " received: " + new String(data));
		nioEngine.send(socketChannel, data);
	}


	public static void main(String[] args) {
		try {
			new Test(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}